package org.jeecg.modules.planProduction.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.planProduction.entity.PlanProductsDetail;
import org.jeecg.modules.planProduction.entity.PlanPartsDetail;
import org.jeecg.modules.planProduction.entity.PlanProduction;
import org.jeecg.modules.planProduction.vo.PlanProductionPage;
import org.jeecg.modules.planProduction.service.IPlanProductionService;
import org.jeecg.modules.planProduction.service.IPlanProductsDetailService;
import org.jeecg.modules.planProduction.service.IPlanPartsDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 生产计划
 * @Author: jeecg-boot
 * @Date:   2025-02-10
 * @Version: V1.0
 */
@Api(tags="生产计划")
@RestController
@RequestMapping("/planProduction/planProduction")
@Slf4j
public class PlanProductionController {
	@Autowired
	private IPlanProductionService planProductionService;
	@Autowired
	private IPlanProductsDetailService planProductsDetailService;
	@Autowired
	private IPlanPartsDetailService planPartsDetailService;

	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 分页列表查询
	 *
	 * @param planProduction
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "生产计划-分页列表查询")
	@ApiOperation(value="生产计划-分页列表查询", notes="生产计划-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PlanProduction planProduction,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PlanProduction> queryWrapper = QueryGenerator.initQueryWrapper(planProduction, req.getParameterMap());
		Page<PlanProduction> page = new Page<PlanProduction>(pageNo, pageSize);
		IPage<PlanProduction> pageList = planProductionService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @AutoLog(value = "生产计划-发布任务")
	 @ApiOperation(value="生产计划-发布任务", notes="生产计划-发布任务")
	 @PostMapping(value = "/release")
	 public Result<?> release(@RequestParam(name = "id") String id) {
		return planProductionService.release(id);
	 }

	 @AutoLog(value = "生产计划-生成部品明细")
	 @ApiOperation(value="生产计划-生成部品明细", notes="生产计划-生成部品明细")
	 @PostMapping(value = "/createPartsDetail")
	 public Result<?> createPartsDetail(@RequestParam(name = "id") String id) {
		 // 异步创建部品明细
		 CompletableFuture.runAsync(() -> planProductionService.createPartsDetail(id))
				 .exceptionally(ex -> {
					 log.error("创建部品明细失败, 生产计划ID: " + id, ex);
					 return null;
				 });
		 return Result.OK("正在生成");
	 }

	 @AutoLog(value = "生产计划-配货完成")
	 @ApiOperation(value="生产计划-配货完成", notes="生产计划-配货完成")
	 @PostMapping(value = "/distribution")
	 public Result<?> distribution(@RequestParam(name = "id") String id) {
		 PlanProduction byId = planProductionService.getById(id);
		 if (byId == null) {
			 return Result.error("未找到对应数据");
		 }
		 if (byId.getStatus() != 2){
			 return Result.error("生产计划不是【已发布】状态,无法配货完成");
		 }
		 byId.setStatus(3);
		 byId.setDistributionTime(new Date());
		 planProductionService.updateById(byId);
		 return Result.OK("配货完成");
	 }
	
	/**
	 *   添加
	 *
	 * @param planProductionPage
	 * @return
	 */
	@AutoLog(value = "生产计划-添加")
	@ApiOperation(value="生产计划-添加", notes="生产计划-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PlanProductionPage planProductionPage) {
		String s = redisUtil.incrementCounter("wms:orderNumber", 5);
		PlanProduction planProduction = new PlanProduction();
		BeanUtils.copyProperties(planProductionPage, planProduction);
		planProduction.setOrderNo(DateUtils.formatDate() + "-" + s);
		planProductionService.saveMain(planProduction, planProductionPage.getPlanProductsDetailList(),planProductionPage.getPlanPartsDetailList());
		// 异步创建部品明细
		CompletableFuture.runAsync(() -> planProductionService.createPartsDetail(planProduction.getId()))
				.exceptionally(ex -> {
					log.error("创建部品明细失败, 生产计划ID: " + planProduction.getId(), ex);
					return null;
				});
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param planProductionPage
	 * @return
	 */
	@AutoLog(value = "生产计划-编辑")
	@ApiOperation(value="生产计划-编辑", notes="生产计划-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PlanProductionPage planProductionPage) {
		PlanProduction planProduction = new PlanProduction();
		BeanUtils.copyProperties(planProductionPage, planProduction);
		PlanProduction planProductionEntity = planProductionService.getById(planProduction.getId());
		if(planProductionEntity==null) {
			return Result.error("未找到对应数据");
		}
		planProductionService.updateMain(planProduction, planProductionPage.getPlanProductsDetailList(),planProductionPage.getPlanPartsDetailList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "生产计划-通过id删除")
	@ApiOperation(value="生产计划-通过id删除", notes="生产计划-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		planProductionService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "生产计划-批量删除")
	@ApiOperation(value="生产计划-批量删除", notes="生产计划-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.planProductionService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "生产计划-通过id查询")
	@ApiOperation(value="生产计划-通过id查询", notes="生产计划-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PlanProduction planProduction = planProductionService.getById(id);
		if(planProduction==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(planProduction);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "制品明细通过主表ID查询")
	@ApiOperation(value="制品明细主表ID查询", notes="制品明细-通主表ID查询")
	@GetMapping(value = "/queryPlanProductsDetailByMainId")
	public Result<?> queryPlanProductsDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PlanProductsDetail> planProductsDetailList = planProductsDetailService.selectByMainId(id);
		return Result.OK(planProductsDetailList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "部品明细通过主表ID查询")
	@ApiOperation(value="部品明细主表ID查询", notes="部品明细-通主表ID查询")
	@GetMapping(value = "/queryPlanPartsDetailByMainId")
	public Result<?> queryPlanPartsDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PlanPartsDetail> planPartsDetailList = planPartsDetailService.selectByMainId(id);
		return Result.OK(planPartsDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param planProduction
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PlanProduction planProduction) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<PlanProduction> queryWrapper = QueryGenerator.initQueryWrapper(planProduction, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<PlanProduction> queryList = planProductionService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<PlanProduction> planProductionList = new ArrayList<PlanProduction>();
      if(oConvertUtils.isEmpty(selections)) {
          planProductionList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          planProductionList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<PlanProductionPage> pageList = new ArrayList<PlanProductionPage>();
      for (PlanProduction main : planProductionList) {
          PlanProductionPage vo = new PlanProductionPage();
          BeanUtils.copyProperties(main, vo);
          List<PlanProductsDetail> planProductsDetailList = planProductsDetailService.selectByMainId(main.getId());
          vo.setPlanProductsDetailList(planProductsDetailList);
          List<PlanPartsDetail> planPartsDetailList = planPartsDetailService.selectByMainId(main.getId());
          vo.setPlanPartsDetailList(planPartsDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "生产计划列表");
      mv.addObject(NormalExcelConstants.CLASS, PlanProductionPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("生产计划数据", "导出人:"+sysUser.getRealname(), "生产计划"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<PlanProductionPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PlanProductionPage.class, params);
              for (PlanProductionPage page : list) {
                  PlanProduction po = new PlanProduction();
                  BeanUtils.copyProperties(page, po);
                  planProductionService.saveMain(po, page.getPlanProductsDetailList(),page.getPlanPartsDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
